package edu.ucla.whi.wanda;

import java.util.LinkedList;
import java.util.List;

import org.restlet.ext.wadl.ParameterInfo;
import org.restlet.ext.wadl.ParameterStyle;
import org.restlet.representation.Representation;
import org.restlet.resource.Post;

import com.amazonaws.services.simpledb.model.PutAttributesRequest;

public abstract class BaseNewResource extends BaseResource {
	private String domain;
	
	public BaseNewResource(String domain) {
		super();
		
		this.domain = domain;
	}

	@Override
	protected List<ParameterInfo> getParams() {
		return postParams();
	}

	@Override
	protected List<ParameterInfo> postParams() {
		List<ParameterInfo> params = new LinkedList<ParameterInfo>();

		// optional
		params.add(new ParameterInfo("Id", false, "xsd:string", ParameterStyle.QUERY, 
				"An optional fixed ID for the entry"));
		
		return params;
	}
	
	@Override
	protected List<ParameterInfo> outputParams() {
		List<ParameterInfo> params = postParams();
		
		// make everything "PLAIN"
		// make "Id" required & change description
		for (ParameterInfo param : params) {
			param.setStyle(ParameterStyle.PLAIN);
			
			if (param.getName() == "Id") {
				param.setRequired(true);
				param.setDocumentation("Unique identifier for the entry");
			}
		}
		
		return params;
	}
	
	@Override
	public Representation get() {
		return post(null);
	}
	
	@Post("txt:json")
	public String newItem(Representation input) {
		String id = params.get("Id") == null ? newId() : params.get("Id");
		getDB().putAttributes(new PutAttributesRequest(domain, id, 
				buildAttributesFromParams(postParams())));

		// for consistent read
		return BaseItemResource.getItem(domain, id, true).toString();
	}
}